package com.example.adminserivce.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.adminserivce.Mapper.StudentMapper;
import com.example.adminserivce.Service.StudentService;
import com.example.common.constants.RdsConstants;
import com.example.common.domain.dto.search.StudentSearchDto;
import com.example.common.domain.pojo.Student;
import com.example.common.utils.CacheClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 学生服务实现类（集成缓存策略）
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    public String key = RdsConstants.STUDENT_INFO;
    @Autowired
    private CacheClient cacheClient;
    @Autowired
    private StudentMapper studentMapper;

    // ======================== 基础 CRUD（带缓存） ========================

    public Page<Student> pageByCriteria(Page<Student> page, StudentSearchDto params) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        if (params.getName() != null && !params.getName().isEmpty()) {
            wrapper.like(Student::getName, params.getName());
        }
        if (params.getMinAge() != null) {
            wrapper.ge(Student::getAge, params.getMinAge());  //大于等于
        }
        if (params.getMaxAge() != null) {
            wrapper.le(Student::getAge, params.getMaxAge());  //小于等于
        }
        if (params.getGender() != null && !params.getGender().isEmpty()) {  //等于
            wrapper.eq(Student::getGender, params.getGender());
        }
        if (params.getMajor() != null && !params.getMajor().isEmpty()) {  //模糊查询
            wrapper.eq(Student::getMajor, params.getMajor());
        }
        return this.page(page, wrapper);
    }

    @Override
    public Student getStudentById(String id) {
        // 使用缓存穿透策略：查询存在性校验 + 空值缓存
        return cacheClient.queryWithPassThrough(
                key,  // Redis 键前缀
                id,                          // 主键ID
                Student.class,                 // 实体类类型
                this::getById,                 // MyBatis-Plus 查询方法
                RdsConstants.CACHE_TTL,        // 正常数据缓存时间（分钟）
                TimeUnit.MINUTES,
                RdsConstants.CACHE_NULL_TTL,   // 空值缓存时间（分钟）
                TimeUnit.MINUTES
        );
    }

    @Override
    public Student getStudentByIdWithLogicalExpire(String id) {
        // 使用逻辑过期策略：过期后异步刷新缓存
        return cacheClient.queryWithLogicalExpire(
                key,
                id,
                Student.class,
                this::getById,
                RdsConstants.CACHE_TTL,
                TimeUnit.MINUTES,
                false  // 是否强制刷新（默认否）
        );
    }

    @Override
    public Student saveStudent(Student student) {
        // 1. 保存到数据库
        boolean success = save(student);
        if (!success) return null;

        // 2. 更新缓存（逻辑过期）
        cacheClient.setWithLogicalExpire(
                key + student.getId(),
                student,
                RdsConstants.CACHE_TTL,
                TimeUnit.MINUTES
        );
        return student;
    }

    @Override
    public Student updateStudent(Student student) {
        // 1. 更新数据库
        boolean success = updateById(student);
        if (!success) return null;

        // 2. 更新缓存（逻辑过期）
        cacheClient.setWithLogicalExpire(
                key + student.getId(),
                student,
                RdsConstants.CACHE_TTL,
                TimeUnit.MINUTES
        );
        return student;
    }

    @Override
    public void deleteStudent(String id) {
        // 1. 删除数据库记录
        removeById(id);

        // 2. 删除缓存
        String cacheKey = RdsConstants.STUDENT_INFO + id;
        cacheClient.delete(cacheKey);
    }


}
